class Layer {
    constructor(method, pathname, callback) {
        this.method = method;
        this.pathname = pathname;
        this.callback = callback;
    }
    match(requestPath, requestMethod) {
        return this.pathname === requestPath && requestMethod === this.method
    }
}

class Router {
    constructor() {
        this.stack = []
    }
    get(pathname, callback) {
        const layer = new Layer('GET', pathname, callback)
        this.stack.push(layer)
    }
    routes() {
        return async (ctx, next) => {
            const requestPath = ctx.path;
            const requestMethod = ctx.method;
            const matchLayers = this.stack.filter(layer => layer.match(requestPath, requestMethod))
            console.log('matchLayers', matchLayers)
            this.compose(matchLayers, ctx, next)
        }
    }
    compose(matchLayers, ctx, next) {
        function dispatch(i) {
            if (i === matchLayers.length) return next()
            return Promise.resolve(matchLayers[i].callback(ctx, () => dispatch(i + 1)))
        }

        return dispatch(0)
    }
}

module.exports = Router